// sfont.go
package sfont

import (
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"os"
	"strings"
)

// FourCC 类型表示 4 字符代码
type FourCC [4]byte

// 一些常用的 FourCC
var (
	RIFF = FourCC{'R', 'I', 'F', 'F'}
	LIST = FourCC{'L', 'I', 'S', 'T'}
	SFBK = FourCC{'s', 'f', 'b', 'k'}
	INFO = FourCC{'I', 'N', 'F', 'O'}
	SDTA = FourCC{'s', 'd', 't', 'a'}
	PDTA = FourCC{'p', 'd', 't', 'a'}
	IFIL = FourCC{'i', 'f', 'i', 'l'}
	ISNG = FourCC{'i', 's', 'n', 'g'}
	INAM = FourCC{'I', 'N', 'A', 'M'}
	IPRD = FourCC{'I', 'P', 'R', 'D'}
	IENG = FourCC{'I', 'E', 'N', 'G'}
	ISFT = FourCC{'I', 'S', 'F', 'T'}
	ICRD = FourCC{'I', 'C', 'R', 'D'}
	ICMT = FourCC{'I', 'C', 'M', 'T'}
	ICOP = FourCC{'I', 'C', 'O', 'P'}
	IROM = FourCC{'i', 'r', 'o', 'm'}
	IVER = FourCC{'i', 'v', 'e', 'r'}
	SMPL = FourCC{'s', 'm', 'p', 'l'}
	PHDR = FourCC{'p', 'h', 'd', 'r'}
	PBAG = FourCC{'p', 'b', 'a', 'g'}
	PMOD = FourCC{'p', 'm', 'o', 'd'}
	PGEN = FourCC{'p', 'g', 'e', 'n'}
	INST = FourCC{'i', 'n', 's', 't'}
	IBAG = FourCC{'i', 'b', 'a', 'g'}
	IMOD = FourCC{'i', 'm', 'o', 'd'}
	IGEN = FourCC{'i', 'g', 'e', 'n'}
	SHDR = FourCC{'s', 'h', 'd', 'r'}
)

// Version 表示版本信息
type Version struct {
	Major uint16
	Minor uint16
}

// Sample 表示音频样本
type Sample struct {
	Name       string
	Start      uint32
	End        uint32
	LoopStart  uint32
	LoopEnd    uint32
	SampleRate uint32
	OrigPitch  uint8
	PitchAdj   int8
	SampleLink uint16
	SampleType uint16
}

// Instrument 表示乐器
type Instrument struct {
	Name               string
	InstrumentBagIndex uint16
	Zones              []*Zone
}

// Preset 表示预设
type Preset struct {
	Name           string
	Preset         uint16
	Bank           uint16
	PresetBagIndex uint16
	Library        uint32
	Genre          uint32
	Morphology     uint32
	Zones          []*Zone
}

// Zone 表示生成器和调制器区域
type Zone struct {
	Generators []*Generator
	Modulators []*Modulator
}

// Generator 表示生成器
type Generator struct {
	Type   GeneratorType
	Amount GeneratorAmount
}

// Modulator 表示调制器
type Modulator struct {
	Source      ModulatorSource
	Destination GeneratorType
	Amount      int16
	AmountSrc   ModulatorSource
	Transform   TransformType
}

// GeneratorType 生成器类型
type GeneratorType uint16

// 生成器类型常量
const (
	Gen_StartAddrOfs           GeneratorType = 0
	Gen_EndAddrOfs             GeneratorType = 1
	Gen_StartLoopAddrOfs       GeneratorType = 2
	Gen_EndLoopAddrOfs         GeneratorType = 3
	Gen_StartAddrCoarseOfs     GeneratorType = 4
	Gen_ModLFO2Pitch           GeneratorType = 5
	Gen_VibLFO2Pitch           GeneratorType = 6
	Gen_ModEnv2Pitch           GeneratorType = 7
	Gen_FilterFc               GeneratorType = 8
	Gen_FilterQ                GeneratorType = 9
	Gen_ModLFO2FilterFc        GeneratorType = 10
	Gen_ModEnv2FilterFc        GeneratorType = 11
	Gen_EndAddrCoarseOfs       GeneratorType = 12
	Gen_ModLFO2Vol             GeneratorType = 13
	Gen_Unused1                GeneratorType = 14
	Gen_ChorusSend             GeneratorType = 15
	Gen_ReverbSend             GeneratorType = 16
	Gen_Pan                    GeneratorType = 17
	Gen_Unused2                GeneratorType = 18
	Gen_Unused3                GeneratorType = 19
	Gen_Unused4                GeneratorType = 20
	Gen_ModLFODelay            GeneratorType = 21
	Gen_ModLFOFreq             GeneratorType = 22
	Gen_VibLFODelay            GeneratorType = 23
	Gen_VibLFOFreq             GeneratorType = 24
	Gen_ModEnvDelay            GeneratorType = 25
	Gen_ModEnvAttack           GeneratorType = 26
	Gen_ModEnvHold             GeneratorType = 27
	Gen_ModEnvDecay            GeneratorType = 28
	Gen_ModEnvSustain          GeneratorType = 29
	Gen_ModEnvRelease          GeneratorType = 30
	Gen_Key2ModEnvHold         GeneratorType = 31
	Gen_Key2ModEnvDecay        GeneratorType = 32
	Gen_VolEnvDelay            GeneratorType = 33
	Gen_VolEnvAttack           GeneratorType = 34
	Gen_VolEnvHold             GeneratorType = 35
	Gen_VolEnvDecay            GeneratorType = 36
	Gen_VolEnvSustain          GeneratorType = 37
	Gen_VolEnvRelease          GeneratorType = 38
	Gen_Key2VolEnvHold         GeneratorType = 39
	Gen_Key2VolEnvDecay        GeneratorType = 40
	Gen_Instrument             GeneratorType = 41
	Gen_Reserved1              GeneratorType = 42
	Gen_KeyRange               GeneratorType = 43
	Gen_VelRange               GeneratorType = 44
	Gen_StartLoopAddrCoarseOfs GeneratorType = 45
	Gen_Keynum                 GeneratorType = 46
	Gen_Velocity               GeneratorType = 47
	Gen_Attenuation            GeneratorType = 48
	Gen_Reserved2              GeneratorType = 49
	Gen_EndLoopAddrCoarseOfs   GeneratorType = 50
	Gen_CoarseTune             GeneratorType = 51
	Gen_FineTune               GeneratorType = 52
	Gen_SampleId               GeneratorType = 53
	Gen_SampleModes            GeneratorType = 54
	Gen_Reserved3              GeneratorType = 55
	Gen_ScaleTune              GeneratorType = 56
	Gen_ExclusiveClass         GeneratorType = 57
	Gen_OverrideRootKey        GeneratorType = 58
	Gen_Dummy                  GeneratorType = 59
)

// GeneratorAmount 生成器值
type GeneratorAmount struct {
	LowByte  uint8
	HighByte uint8
	Word     uint16
	Short    int16
}

// ModulatorSource 调制器源
type ModulatorSource uint16

// TransformType 变换类型
type TransformType uint16

// 预设包（Preset Bag）结构
type PresetBag struct {
	GeneratorIndex uint16
	ModulatorIndex uint16
}

// 乐器包（Instrument Bag）结构
type InstrumentBag struct {
	GeneratorIndex uint16
	ModulatorIndex uint16
}

// SoundFont 表示整个 SoundFont 文件
type SoundFont struct {
	Path      string
	Version   Version
	IVersion  Version
	Name      string
	Engine    string
	Date      string
	Comment   string
	Tools     string
	Creator   string
	Product   string
	Copyright string
	IROM      string

	Presets     []*Preset
	Instruments []*Instrument
	Samples     []*Sample

	SampleData []byte
	samplePos  int64

	// 区域和生成器数据
	PresetBags []PresetBag
	PresetGens []Generator
	PresetMods []Modulator

	InstrumentBags []InstrumentBag
	InstrumentGens []Generator
	InstrumentMods []Modulator

	// 索引映射
	presetZoneIndices     []int // 每个预设的区域起始索引
	instrumentZoneIndices []int // 每个乐器的区域起始索引
}

// Reader 用于读取 SoundFont 文件
type Reader struct {
	r   io.ReadSeeker
	pos int64
}

// NewReader 创建新的 SoundFont 读取器
func NewReader(r io.ReadSeeker) *Reader {
	return &Reader{r: r}
}

// Read 读取 SoundFont 文件
func (sf *SoundFont) Read(filename string) error {
	file, err := os.Open(filename)
	if err != nil {
		return fmt.Errorf("无法打开文件: %v", err)
	}
	defer file.Close()

	sf.Path = filename
	reader := NewReader(file)

	// 读取 RIFF 头
	chunkID, err := reader.ReadFourCC()
	if err != nil {
		return err
	}
	if chunkID != RIFF {
		return errors.New("不是有效的 RIFF 文件")
	}

	chunkSize, err := reader.ReadUint32()
	if err != nil {
		return err
	}

	format, err := reader.ReadFourCC()
	if err != nil {
		return err
	}
	if format != SFBK {
		return errors.New("不是 SoundFont 文件")
	}

	// 读取各个块
	remaining := int64(chunkSize) - 4
	for remaining > 0 {
		chunkID, err := reader.ReadFourCC()
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}

		chunkSize, err := reader.ReadUint32()
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}

		if chunkID == LIST {
			listType, err := reader.ReadFourCC()
			if err != nil {
				return err
			}

			err = sf.readListChunk(reader, listType, int64(chunkSize)-4)
			if err != nil {
				return err
			}

			remaining -= 8 + int64(chunkSize)
		} else {
			// 读取独立块
			err = sf.readSingleChunk(reader, chunkID, chunkSize)
			if err != nil {
				return err
			}
			remaining -= 8 + int64(chunkSize)
		}

		if remaining < 0 {
			break
		}
	}

	// 建立预设和乐器的区域链接
	sf.linkPresetZones()
	sf.linkInstrumentZones()

	return nil
}

// readListChunk 读取 LIST 块
func (sf *SoundFont) readListChunk(reader *Reader, listType FourCC, size int64) error {
	startPos, _ := reader.Seek(0, io.SeekCurrent)
	endPos := startPos + size

	for {
		currentPos, _ := reader.Seek(0, io.SeekCurrent)
		if currentPos >= endPos {
			break
		}

		chunkID, err := reader.ReadFourCC()
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}

		chunkSize, err := reader.ReadUint32()
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}

		switch listType {
		case INFO:
			err = sf.readInfoChunk(reader, chunkID, chunkSize)
		case SDTA:
			err = sf.readSampleDataChunk(reader, chunkID, chunkSize)
		case PDTA:
			err = sf.readPresetDataChunk(reader, chunkID, chunkSize)
		default:
			reader.Seek(int64(chunkSize), io.SeekCurrent)
		}

		if err != nil {
			return err
		}

		// 检查是否到达列表结尾
		currentPos, _ = reader.Seek(0, io.SeekCurrent)
		if currentPos >= endPos {
			break
		}
	}

	return nil
}

// readSingleChunk 读取独立块
func (sf *SoundFont) readSingleChunk(reader *Reader, chunkID FourCC, size uint32) error {
	switch chunkID {
	case SMPL:
		return sf.readSampleDataChunk(reader, chunkID, size)
	default:
		reader.Seek(int64(size), io.SeekCurrent)
	}
	return nil
}

// readInfoChunk 读取 INFO 块
func (sf *SoundFont) readInfoChunk(reader *Reader, chunkID FourCC, size uint32) error {
	switch chunkID {
	case IFIL:
		major, err := reader.ReadUint16()
		if err != nil {
			return err
		}
		minor, err := reader.ReadUint16()
		if err != nil {
			return err
		}
		sf.Version = Version{Major: major, Minor: minor}
	case INAM:
		name, err := reader.ReadString(int(size))
		if err != nil {
			return err
		}
		sf.Name = strings.Trim(name, "\x00")
	case ISNG:
		engine, err := reader.ReadString(int(size))
		if err != nil {
			return err
		}
		sf.Engine = strings.Trim(engine, "\x00")
	case IPRD:
		product, err := reader.ReadString(int(size))
		if err != nil {
			return err
		}
		sf.Product = strings.Trim(product, "\x00")
	case IENG:
		creator, err := reader.ReadString(int(size))
		if err != nil {
			return err
		}
		sf.Creator = strings.Trim(creator, "\x00")
	case ISFT:
		tools, err := reader.ReadString(int(size))
		if err != nil {
			return err
		}
		sf.Tools = strings.Trim(tools, "\x00")
	case ICRD:
		date, err := reader.ReadString(int(size))
		if err != nil {
			return err
		}
		sf.Date = strings.Trim(date, "\x00")
	case ICMT:
		comment, err := reader.ReadString(int(size))
		if err != nil {
			return err
		}
		sf.Comment = strings.Trim(comment, "\x00")
	case ICOP:
		copyright, err := reader.ReadString(int(size))
		if err != nil {
			return err
		}
		sf.Copyright = strings.Trim(copyright, "\x00")
	case IROM:
		irom, err := reader.ReadString(int(size))
		if err != nil {
			return err
		}
		sf.IROM = strings.Trim(irom, "\x00")
	case IVER:
		major, err := reader.ReadUint16()
		if err != nil {
			return err
		}
		minor, err := reader.ReadUint16()
		if err != nil {
			return err
		}
		sf.IVersion = Version{Major: major, Minor: minor}
	default:
		reader.Seek(int64(size), io.SeekCurrent)
	}
	return nil
}

// readSampleDataChunk 读取样本数据块
func (sf *SoundFont) readSampleDataChunk(reader *Reader, chunkID FourCC, size uint32) error {
	if chunkID == SMPL {
		// 记录样本数据位置
		sf.samplePos, _ = reader.Seek(0, io.SeekCurrent)
		sf.SampleData = make([]byte, size)
		_, err := reader.Read(sf.SampleData)
		return err
	}
	reader.Seek(int64(size), io.SeekCurrent)
	return nil
}

// readPresetDataChunk 读取预设数据块
func (sf *SoundFont) readPresetDataChunk(reader *Reader, chunkID FourCC, size uint32) error {
	switch chunkID {
	case PHDR:
		return sf.readPresetHeaders(reader, size)
	case PBAG:
		return sf.readPresetBags(reader, size)
	case PMOD:
		return sf.readPresetModulators(reader, size)
	case PGEN:
		return sf.readPresetGenerators(reader, size)
	case INST:
		return sf.readInstruments(reader, size)
	case IBAG:
		return sf.readInstrumentBags(reader, size)
	case IMOD:
		return sf.readInstrumentModulators(reader, size)
	case IGEN:
		return sf.readInstrumentGenerators(reader, size)
	case SHDR:
		return sf.readSampleHeaders(reader, size)
	default:
		reader.Seek(int64(size), io.SeekCurrent)
	}
	return nil
}

// readPresetHeaders 读取预设头
func (sf *SoundFont) readPresetHeaders(reader *Reader, size uint32) error {
	count := size / 38
	if count <= 1 {
		return nil
	}

	for i := 0; i < int(count); i++ {
		preset := &Preset{}

		name, err := reader.ReadString(20)
		if err != nil {
			return err
		}
		preset.Name = strings.Trim(name, "\x00")

		preset.Preset, err = reader.ReadUint16()
		if err != nil {
			return err
		}

		preset.Bank, err = reader.ReadUint16()
		if err != nil {
			return err
		}

		preset.PresetBagIndex, err = reader.ReadUint16()
		if err != nil {
			return err
		}

		preset.Library, err = reader.ReadUint32()
		if err != nil {
			return err
		}

		preset.Genre, err = reader.ReadUint32()
		if err != nil {
			return err
		}

		preset.Morphology, err = reader.ReadUint32()
		if err != nil {
			return err
		}

		// 最后一个预设是终止符，不添加到列表
		if i < int(count)-1 {
			sf.Presets = append(sf.Presets, preset)
		}
	}

	return nil
}

// readInstruments 读取乐器
func (sf *SoundFont) readInstruments(reader *Reader, size uint32) error {
	count := size / 22
	if count <= 1 {
		return nil
	}

	for i := 0; i < int(count); i++ {
		instrument := &Instrument{}

		name, err := reader.ReadString(20)
		if err != nil {
			return err
		}
		instrument.Name = strings.Trim(name, "\x00")

		instrument.InstrumentBagIndex, err = reader.ReadUint16()
		if err != nil {
			return err
		}

		// 最后一个乐器是终止符，不添加到列表
		if i < int(count)-1 {
			sf.Instruments = append(sf.Instruments, instrument)
		}
	}

	return nil
}

// readSampleHeaders 读取样本头
func (sf *SoundFont) readSampleHeaders(reader *Reader, size uint32) error {
	count := size / 46
	if count <= 1 {
		return nil
	}

	for i := 0; i < int(count); i++ {
		sample := &Sample{}

		name, err := reader.ReadString(20)
		if err != nil {
			return err
		}
		sample.Name = strings.Trim(name, "\x00")

		sample.Start, err = reader.ReadUint32()
		if err != nil {
			return err
		}

		sample.End, err = reader.ReadUint32()
		if err != nil {
			return err
		}

		sample.LoopStart, err = reader.ReadUint32()
		if err != nil {
			return err
		}

		sample.LoopEnd, err = reader.ReadUint32()
		if err != nil {
			return err
		}

		sample.SampleRate, err = reader.ReadUint32()
		if err != nil {
			return err
		}

		sample.OrigPitch, err = reader.ReadUint8()
		if err != nil {
			return err
		}

		pitchAdj, err := reader.ReadInt8()
		if err != nil {
			return err
		}
		sample.PitchAdj = pitchAdj

		sample.SampleLink, err = reader.ReadUint16()
		if err != nil {
			return err
		}

		sample.SampleType, err = reader.ReadUint16()
		if err != nil {
			return err
		}

		// 最后一个样本是终止符，不添加到列表
		if i < int(count)-1 {
			sf.Samples = append(sf.Samples, sample)
		}
	}

	return nil
}

// 读取预设包
func (sf *SoundFont) readPresetBags(reader *Reader, size uint32) error {
	if size%4 != 0 {
		return fmt.Errorf("预设包大小不是4的倍数: %d", size)
	}

	count := size / 4
	sf.PresetBags = make([]PresetBag, count)

	for i := uint32(0); i < count; i++ {
		genIndex, err := reader.ReadUint16()
		if err != nil {
			return err
		}
		modIndex, err := reader.ReadUint16()
		if err != nil {
			return err
		}

		sf.PresetBags[i] = PresetBag{
			GeneratorIndex: genIndex,
			ModulatorIndex: modIndex,
		}
	}

	return nil
}

// 读取预设生成器
func (sf *SoundFont) readPresetGenerators(reader *Reader, size uint32) error {
	if size%4 != 0 {
		return fmt.Errorf("预设生成器大小不是4的倍数: %d", size)
	}

	count := size / 4
	sf.PresetGens = make([]Generator, count)

	for i := uint32(0); i < count; i++ {
		genType, err := reader.ReadUint16()
		if err != nil {
			return err
		}

		var amount GeneratorAmount
		if GeneratorType(genType) == Gen_KeyRange || GeneratorType(genType) == Gen_VelRange {
			lo, err := reader.ReadUint8()
			if err != nil {
				return err
			}
			hi, err := reader.ReadUint8()
			if err != nil {
				return err
			}
			amount.LowByte = lo
			amount.HighByte = hi
		} else {
			word, err := reader.ReadUint16()
			if err != nil {
				return err
			}
			amount.Word = word
			amount.Short = int16(word)
		}

		sf.PresetGens[i] = Generator{
			Type:   GeneratorType(genType),
			Amount: amount,
		}
	}

	return nil
}

// 读取乐器包
func (sf *SoundFont) readInstrumentBags(reader *Reader, size uint32) error {
	if size%4 != 0 {
		return fmt.Errorf("乐器包大小不是4的倍数: %d", size)
	}

	count := size / 4
	sf.InstrumentBags = make([]InstrumentBag, count)

	for i := uint32(0); i < count; i++ {
		genIndex, err := reader.ReadUint16()
		if err != nil {
			return err
		}
		modIndex, err := reader.ReadUint16()
		if err != nil {
			return err
		}

		sf.InstrumentBags[i] = InstrumentBag{
			GeneratorIndex: genIndex,
			ModulatorIndex: modIndex,
		}
	}

	return nil
}

// 读取乐器生成器
func (sf *SoundFont) readInstrumentGenerators(reader *Reader, size uint32) error {
	if size%4 != 0 {
		return fmt.Errorf("乐器生成器大小不是4的倍数: %d", size)
	}

	count := size / 4
	sf.InstrumentGens = make([]Generator, count)

	for i := uint32(0); i < count; i++ {
		genType, err := reader.ReadUint16()
		if err != nil {
			return err
		}

		var amount GeneratorAmount
		if GeneratorType(genType) == Gen_KeyRange || GeneratorType(genType) == Gen_VelRange {
			lo, err := reader.ReadUint8()
			if err != nil {
				return err
			}
			hi, err := reader.ReadUint8()
			if err != nil {
				return err
			}
			amount.LowByte = lo
			amount.HighByte = hi
		} else {
			word, err := reader.ReadUint16()
			if err != nil {
				return err
			}
			amount.Word = word
			amount.Short = int16(word)
		}

		sf.InstrumentGens[i] = Generator{
			Type:   GeneratorType(genType),
			Amount: amount,
		}
	}

	return nil
}

// 读取预设调制器（占位实现）
func (sf *SoundFont) readPresetModulators(reader *Reader, size uint32) error {
	reader.Seek(int64(size), io.SeekCurrent)
	return nil
}

// 读取乐器调制器（占位实现）
func (sf *SoundFont) readInstrumentModulators(reader *Reader, size uint32) error {
	reader.Seek(int64(size), io.SeekCurrent)
	return nil
}

// 链接预设区域
func (sf *SoundFont) linkPresetZones() {
	if len(sf.Presets) == 0 || len(sf.PresetBags) == 0 {
		return
	}

	// 建立预设区域索引
	sf.presetZoneIndices = make([]int, len(sf.Presets)+1)
	for i, preset := range sf.Presets {
		sf.presetZoneIndices[i] = int(preset.PresetBagIndex)
	}
	// 最后一个索引指向包列表的末尾
	sf.presetZoneIndices[len(sf.Presets)] = len(sf.PresetBags) - 1

	// 为每个预设创建区域
	for i, preset := range sf.Presets {
		startIdx := sf.presetZoneIndices[i]
		endIdx := sf.presetZoneIndices[i+1]

		for j := startIdx; j < endIdx; j++ {
			zone := &Zone{}
			bag := sf.PresetBags[j]

			// 添加生成器到区域
			genStart := bag.GeneratorIndex
			var genEnd uint16
			if j+1 < len(sf.PresetBags) {
				genEnd = sf.PresetBags[j+1].GeneratorIndex
			} else {
				genEnd = uint16(len(sf.PresetGens))
			}

			for k := genStart; k < genEnd; k++ {
				if int(k) < len(sf.PresetGens) {
					// 创建生成器的副本，避免引用问题
					gen := sf.PresetGens[k]
					zone.Generators = append(zone.Generators, &gen)
				}
			}

			preset.Zones = append(preset.Zones, zone)
		}
	}
}

// 链接乐器区域
func (sf *SoundFont) linkInstrumentZones() {
	if len(sf.Instruments) == 0 || len(sf.InstrumentBags) == 0 {
		return
	}

	// 建立乐器区域索引
	sf.instrumentZoneIndices = make([]int, len(sf.Instruments)+1)
	for i, inst := range sf.Instruments {
		sf.instrumentZoneIndices[i] = int(inst.InstrumentBagIndex)
	}
	// 最后一个索引指向包列表的末尾
	sf.instrumentZoneIndices[len(sf.Instruments)] = len(sf.InstrumentBags) - 1

	// 为每个乐器创建区域
	for i, inst := range sf.Instruments {
		startIdx := sf.instrumentZoneIndices[i]
		endIdx := sf.instrumentZoneIndices[i+1]

		for j := startIdx; j < endIdx; j++ {
			zone := &Zone{}
			bag := sf.InstrumentBags[j]

			// 添加生成器到区域
			genStart := bag.GeneratorIndex
			var genEnd uint16
			if j+1 < len(sf.InstrumentBags) {
				genEnd = sf.InstrumentBags[j+1].GeneratorIndex
			} else {
				genEnd = uint16(len(sf.InstrumentGens))
			}

			for k := genStart; k < genEnd; k++ {
				if int(k) < len(sf.InstrumentGens) {
					// 创建生成器的副本，避免引用问题
					gen := sf.InstrumentGens[k]
					zone.Generators = append(zone.Generators, &gen)
				}
			}

			inst.Zones = append(inst.Zones, zone)
		}
	}
}

// GetPresetZoneCount 获取预设的区域数量
func (sf *SoundFont) GetPresetZoneCount(presetIndex int) int {
	if presetIndex < 0 || presetIndex >= len(sf.presetZoneIndices)-1 {
		return 0
	}
	startIdx := sf.presetZoneIndices[presetIndex]
	endIdx := sf.presetZoneIndices[presetIndex+1]
	return endIdx - startIdx
}

// GetInstrumentZoneCount 获取乐器的区域数量
func (sf *SoundFont) GetInstrumentZoneCount(instrumentIndex int) int {
	if instrumentIndex < 0 || instrumentIndex >= len(sf.instrumentZoneIndices)-1 {
		return 0
	}
	startIdx := sf.instrumentZoneIndices[instrumentIndex]
	endIdx := sf.instrumentZoneIndices[instrumentIndex+1]
	return endIdx - startIdx
}

// FindPresetInstruments 查找预设引用的乐器
func (sf *SoundFont) FindPresetInstruments(presetIndex int) []*Instrument {
	if presetIndex < 0 || presetIndex >= len(sf.Presets) {
		return nil
	}

	preset := sf.Presets[presetIndex]
	var instruments []*Instrument

	for _, zone := range preset.Zones {
		for _, gen := range zone.Generators {
			if gen.Type == Gen_Instrument {
				instIndex := int(gen.Amount.Word)
				if instIndex >= 0 && instIndex < len(sf.Instruments) {
					instruments = append(instruments, sf.Instruments[instIndex])
				}
			}
		}
	}

	return instruments
}

// FindInstrumentSamples 查找乐器引用的样本
func (sf *SoundFont) FindInstrumentSamples(instrumentIndex int) []*Sample {
	if instrumentIndex < 0 || instrumentIndex >= len(sf.Instruments) {
		return nil
	}

	instrument := sf.Instruments[instrumentIndex]
	var samples []*Sample

	for _, zone := range instrument.Zones {
		for _, gen := range zone.Generators {
			if gen.Type == Gen_SampleId {
				sampleIndex := int(gen.Amount.Word)
				if sampleIndex >= 0 && sampleIndex < len(sf.Samples) {
					samples = append(samples, sf.Samples[sampleIndex])
				}
			}
		}
	}

	return samples
}

// GetPresetByBankProgram 根据银行号和预设号查找预设
func (sf *SoundFont) GetPresetByBankProgram(bank, program uint16) *Preset {
	for _, preset := range sf.Presets {
		if preset.Bank == bank && preset.Preset == program {
			return preset
		}
	}
	return nil
}

// GetInstrumentByName 根据名称查找乐器
func (sf *SoundFont) GetInstrumentByName(name string) *Instrument {
	for _, inst := range sf.Instruments {
		if inst.Name == name {
			return inst
		}
	}
	return nil
}

// GetSampleByName 根据名称查找样本
func (sf *SoundFont) GetSampleByName(name string) *Sample {
	for _, sample := range sf.Samples {
		if sample.Name == name {
			return sample
		}
	}
	return nil
}

// GetTotalSampleSize 获取样本数据的总大小（字节）
func (sf *SoundFont) GetTotalSampleSize() int64 {
	if sf.SampleData == nil {
		return 0
	}
	return int64(len(sf.SampleData))
}

// GetSampleDuration 获取样本的持续时间（秒）
func (sf *SoundFont) GetSampleDuration(sample *Sample) float64 {
	if sample.SampleRate == 0 {
		return 0
	}
	samplePoints := sample.End - sample.Start
	return float64(samplePoints) / float64(sample.SampleRate)
}

// IsSampleLooped 检查样本是否有循环
func (sf *SoundFont) IsSampleLooped(sample *Sample) bool {
	return sample.LoopStart != sample.LoopEnd
}

// GetSampleAudioData 获取样本的音频数据
func (sf *SoundFont) GetSampleAudioData(sample *Sample) ([]int16, error) {
	if sf.SampleData == nil {
		return nil, errors.New("没有样本数据")
	}

	if sample.Start >= sample.End {
		return nil, errors.New("样本起始位置大于等于结束位置")
	}

	start := sample.Start * 2 // 16-bit samples, so 2 bytes per sample
	end := sample.End * 2

	if end > uint32(len(sf.SampleData)) {
		return nil, errors.New("样本数据超出范围")
	}

	data := sf.SampleData[start:end]
	samples := make([]int16, len(data)/2)

	for i := 0; i < len(samples); i++ {
		samples[i] = int16(binary.LittleEndian.Uint16(data[i*2 : (i+1)*2]))
	}

	return samples, nil
}

// Reader 方法实现

func (r *Reader) ReadFourCC() (FourCC, error) {
	var fourcc FourCC
	err := binary.Read(r.r, binary.LittleEndian, &fourcc)
	return fourcc, err
}

func (r *Reader) ReadUint32() (uint32, error) {
	var value uint32
	err := binary.Read(r.r, binary.LittleEndian, &value)
	return value, err
}

func (r *Reader) ReadUint16() (uint16, error) {
	var value uint16
	err := binary.Read(r.r, binary.LittleEndian, &value)
	return value, err
}

func (r *Reader) ReadInt16() (int16, error) {
	var value int16
	err := binary.Read(r.r, binary.LittleEndian, &value)
	return value, err
}

func (r *Reader) ReadUint8() (uint8, error) {
	var value uint8
	err := binary.Read(r.r, binary.LittleEndian, &value)
	return value, err
}

func (r *Reader) ReadInt8() (int8, error) {
	var value int8
	err := binary.Read(r.r, binary.LittleEndian, &value)
	return value, err
}

func (r *Reader) ReadString(length int) (string, error) {
	buf := make([]byte, length)
	_, err := r.r.Read(buf)
	if err != nil {
		return "", err
	}
	return string(buf), nil
}

func (r *Reader) Read(data []byte) (int, error) {
	return r.r.Read(data)
}

func (r *Reader) Seek(offset int64, whence int) (int64, error) {
	return r.r.Seek(offset, whence)
}

// FindSamplesByName 根据名称查找样本（支持通配符）
func (sf *SoundFont) FindSamplesByName(pattern string) []*Sample {
	var matched []*Sample
	pattern = strings.ToLower(pattern)

	for _, sample := range sf.Samples {
		if strings.Contains(strings.ToLower(sample.Name), pattern) {
			matched = append(matched, sample)
		}
	}

	return matched
}
